var AppComm={};
AppComm.log = function(msg){
    if (typeof console == "object") {
        console.log(msg);
    }
};

AppComm.initFrame = function(pageObject){
    pageObject.event ={
        'isReaded': false,
        onReady: function () {
            pageObject.action.initBody();

            // $('.layui-tab-title').on('click', function(title) {
            //     // 切换tab后重新显示滚动条
            //     AppComm.utils.resizeScroll();
            // });
        }
    };
    //页面加载完后执行
    AppComm.action.ready(function () {
        if (!pageObject.event.isReaded) {
            pageObject.event.isReaded = true;
            pageObject.event.onReady();
        }
    });
};

AppComm.action = {
    ready: function(onReady) {
        !function($) {
            $(function() {
               onReady();
            });
        }(window.jQuery);

        // 统一处理ajax异常
        $(document).ajaxError(
            //所有ajax请求异常的统一处理函数，处理
            function(event,xhr,options,exc ){
                if(xhr.status == 'undefined'){
                    return;
                }
                switch(xhr.status){
                    case 403:
                        // 未授权异常
                        layer.msg("系统拒绝：您没有访问权限。", {icon: 5});
                        break;
                    case 404:
                        layer.msg("您访问的资源不存在。", {icon: 5});
                        break;
                    case 300:
                        // alert("ddd");
                        break;
                    case 200:
                        if (xhr.statusText=='parsererror') {
                            layer.confirm('登录过期，请重新登录。',{icon: 3, title:'提示'},function(index){
                                window.location.reload();
                                layer.close(index);
                            }, function(index){
                                layer.close(index);
                            });
                        }
                        break;
                    default:
                        console.log("状态码："+xhr.status, {icon: 7});
                        break;
                }
                return;
            }
        );
    }
};


AppComm.ajax = {
    'cache':{
        'needLogin':false
    },
    execute: function(options) {
        var mergedOption = $.extend({},{
            'url':undefined,
            'dataType':'json',
            'processData': false,
            'contentType': 'application/json',
            // 'async':true,
            'data':{},
            'beforeSend':function(){},
            'success': function () {},
            'error':function(){},
            'type':'POST',
            'complete':function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.responseJSON) {
                    var httpStatus = XMLHttpRequest.responseJSON.httpStatus;
                    console.log(XMLHttpRequest.responseJSON.code);
                    console.log(httpStatus);
                    if (httpStatus == '403') {
                        layer.msg(XMLHttpRequest.responseJSON.message, {icon: 5});
                        return;
                    } else if(XMLHttpRequest.responseJSON.code==Enums.ResultEnum().FAILURE.code){
                        if (XMLHttpRequest.responseJSON.msg=='UnauthenticatedException') {
                            layer.confirm('登录过期，请重新登录。',{icon: 3, title:'提示'},function(index){
                                window.location.reload();
                                layer.close(index);
                            }, function(index){
                                layer.close(index);
                            });
                        }
                        // else {
                        //     layer.msg(XMLHttpRequest.responseJSON.msg, {icon: 5});
                        // }
                        return;
                    }
                }
            }
        },{
        },options);

        $.ajax(mergedOption);

    },
    onSuccess: function(resultData){
        if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
            if (resultData.msg != null && resultData.msg != '') {
                AppComm.notice.success(resultData.msg);
            }
        } else {
            if (resultData.msg != null && resultData.msg != '') {
                AppComm.notice.error(resultData.msg);
            }
        }
    },
    post: function (url, data, successCallback) {
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + url,
            'data': JSON.stringify(data),
            'method': 'POST',
            'success': function (resultData) {
                if (typeof successCallback=='function') {
                    successCallback(resultData);
                } else {
                    AppComm.ajax.onSuccess(resultData);
                }
            }
        });
    },
    get: function (url, data, successCallback) {
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + url,
            'data': JSON.stringify(data),
            'method': 'get',
            'success': function (resultData) {
                if (typeof successCallback=='function') {
                    successCallback(resultData);
                } else {
                    AppComm.ajax.onSuccess(resultData);
                }
            }
        });
    }
};

AppComm.type = {
    isString:function(data){
        var isString = (typeof data=='string');
        isString = isString && (data.constructor==string);
        return isString;
    }
};

AppComm.include = {
    data:{
        cache:{
            'version':undefined
        },
        getVersion:function(){
            var thisVersion = AppComm.include.data.cache.version;
            if (!thisVersion) {
                var scriptLoader = $('[data-toggle="jsConfig"]');
                thisVersion = scriptLoader.attr('data-version');
                // 如果明确设置了变量的值（非null/undifined/0/""等值),
                // 结果就会根据变量的实际值来返回，如果没有设置，结果就会返回false
                if (!!thisVersion){
                    AppComm.include.data.cache.version = thisVersion;
                }
            }
            return thisVersion;
        }
    },
    loadCss: function (url,ver) {
        var urlExtend= !!ver ? '?_ver'+ver : "";
        $("<link>").attr({
            rel:"stylesheet",
            type:"text/css",
            href:(url+urlExtend),
            ctx:"menu"
        }).appendTo("head");
    },
    loadJs: function(url, ver){
        var script = document.createElement("script");
        script.src = !!ver ? (url+'?_ver='+ver) : url;
        document.head.appendChild(script);
    },
    load:function (urlsStr, urlType) {
        urls = urlsStr.split(',');
        var specVersion = AppComm.include.data.getVersion();
        for (var i=0; i<urls.length; i++) {
            try{
                switch(urlType) {
                    case 'css':
                        AppComm.include.loadCss(urls[i],specVersion);
                        break;
                    case 'js':
                    {
                        AppComm.include.loadJs(urls[i], specVersion);
                        break;
                    }
                    default:
                        if (urls[i].indexOf('.css') >= 0){
                            AppComm.include.loadCss(urls[i], specVersion);
                        } else {
                            AppComm.include.loadJs(urls[i], specVersion);
                        }
                        break;
                }
            } catch (e) {

            }
        }
    }
};

AppComm.url = {
    replaceWithUrl:function(url){
        window.location.href=url;
    },
    getBaseURL: function() {
        var fullPath = window.document.location.href;
        var pathName = window.document.location.pathname;
        var hostPath = fullPath.substring(0, fullPath.indexOf(pathName));
        // var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
        var projectName = $("#contextPath").val();
        if (projectName==null || projectName==undefined ) {
            var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
        }
        var baseURL = hostPath + projectName;
        // alert(baseURL);
        return baseURL;
    },
    getUrlParam: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return decodeURIComponent(r[2]); return null; //返回参数值
    }
};

AppComm.date={
    formatDate:function (format, timeObject) {
        if(!timeObject)return "";
        try {
            var o =
            {
                "M+" : timeObject.getMonth()+1, //month
                "d+" : timeObject.getDate(),    //day
                "h+" : timeObject.getHours(),   //hour
                "m+" : timeObject.getMinutes(), //minute
                "s+" : timeObject.getSeconds(), //second
                "q+" : Math.floor((timeObject.getMonth()+3)/3),  //quarter
                "S" : timeObject.getMilliseconds() //millisecond
            }
            if(/(y+)/.test(format))
                format=format.replace(RegExp.$1,(timeObject.getFullYear()+"").substr(4 - RegExp.$1.length));
            for(var k in o)
                if(new RegExp("("+ k +")").test(format))
                    format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
            return format;
        }catch(e){}
        return "";
    },
};

AppComm.data= {
    // 创建返回对象
    newResult: function () {
        return  {
            code:Enums.ResultEnum().SUCCESS.code,
            msg:""
        }
    },

};

AppComm.permission={
    hasPermission:function (permissionKey) {
        var result=false;
        if (permissionKey==undefined || permissionKey==null || permissionKey=="") {
            return false;
        }
        var params = {
            permissionKey:permissionKey
        };
        var onSuccess = function (resultData) {
            if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
                result = resultData.data;
            }
            return;
        };
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + '/permission/ajax/hasPermission',
            'data':params,
            'async':false,
            'success': onSuccess
        });
        return result;
    },
    isAdministrator:function () {
        var result=false;
        var onSuccess = function (resultData) {
            if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
                result = resultData.data;
            }
            return;
        };
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + '/permission/ajax/isAdministrator',
            'data':null,
            'async':false,
            'success': onSuccess
        });
        return result;
    }
};

AppComm.utils={
    random: function (lower, upper) {
        return Math.floor(Math.random() * (upper - lower+1)) + lower;
    },
    initScroll: function(dom) {
        dom.niceScroll({
            cursorcolor: "#a1a5a8", //滚动条的颜色
            cursoropacitymax: 1, //滚动条的透明度，从0-1
            touchbehavior: false, //使光标拖动滚动像在台式电脑触摸设备
            cursorwidth: "8px", //滚动条的宽度
            cursorborder: "0", // 游标边框css定义
            cursorborderradius: "5px", //以像素为光标边界半径  圆角
            autohidemode: false, //是否隐藏滚动条  true的时候默认不显示滚动条，当鼠标经过的时候显示滚动条
            zindex: "auto", //给滚动条设置z-index值
            railpadding: {
                top: 0,
                right: 0,
                left: 0,
                bottom: 0
            }, //滚动条的位置
        });
    },
    resizeScroll: function(dom) {
        setTimeout(function () {
            if (dom == null) {
                $("#admin-body").getNiceScroll().resize();
            } else {
                dom.getNiceScroll().resize();
            }
        }, 1000)
    },
    /**
     * 对用户名和密码明文进行加密（依赖于MD5.js）
     * @param username
     * @param password
     * @returns {string}
     */
    md5: function(username,password) {
        return MD5(username +"~" + password);
    },
    /**
     * 当前的iframe子窗口
     * @param layerObject
     * @returns {Window}
     */
    iframeWin:function (layerObject) {
        return window[layerObject.find('iframe')[0]['name']];
    },
    /**
     * iframe层的高度会重新进行适应
     */
    iframeAuto:function () {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.iframeAuto(index);
    },
    iframeCloseSelf:function () {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    }
};

AppComm.notice={
    success:function (msg) {
        layui.use(['notice'], function () {

            // AppComm.utils.iframeWin();
            var notice = layui.notice;
            notice.success(msg);
        });
    },
    info:function (msg) {
        layui.use(['notice'], function () {
            var notice = layui.notice;
            notice.info(msg);
        });
    },
    warning:function (msg) {
        layui.use(['notice'], function () {
            var notice = layui.notice;
            notice.warning(msg);
        });
    },
    error:function (msg) {
        layui.use(['notice'], function () {
            var notice = layui.notice;
            notice.error(msg);
        });
    },
};

AppComm.layer={
    // 友情提示
    warm:function(msg){
        layer.alert(msg, {
            icon: 0,
            skin: 'layer-ext-moon'
        })
    },
    confirm:function(msg, callback){
        layer.confirm(msg, {icon: 3, title: '提示'}, function (index) {
            if (typeof callback == 'function') {
                callback();
            }
            layer.close(index);
        }, function (index) {
            layer.close(index);
        });
    },
    getOpenWidthHeight: function (area) {
        var clienWidth = $(".frame-content-page").width();
        var clientHeight = $(".frame-content-page").height();
        var offsetLeft;
        if ($(".frame-content-page").offset()!=undefined) {
            offsetLeft = $(".frame-content-page").offset().left;
        }
        var offsetTop;
        if ($(".frame-content-page").offset()!=undefined) {
            offsetTop = $(".frame-content-page").offset().top;
        }
        if (area!=null && area!='') {
            clienWidth = area[0];
            clientHeight = area[1];
            offsetLeft = area[2];
            offsetTop = area[3];
        }
        return [clienWidth, clientHeight, offsetTop, offsetLeft];
    },
    open:function(url, area, successCallback){
        layer.open({
            type: 2,
            shadeClose: true,
            content: AppComm.url.getBaseURL()+url,
            // area: ['720px', '430px'],
            area: [AppComm.layer.getOpenWidthHeight(area)[0] + 'px', AppComm.layer.getOpenWidthHeight(area)[1] + 'px'],
            offset: [AppComm.layer.getOpenWidthHeight(area)[2] + 'px', AppComm.layer.getOpenWidthHeight(area)[3] + 'px'],
            scrollbar: false,
            maxmin: true,
            success: function (layero, index) {
                if (typeof successCallback == 'function') {
                    successCallback(layero, index);
                }
            }
        });
    },
    openWindow:function(url, successCallback) {
        var newWindow = window.open(AppComm.url.getBaseURL()+url);
        if (typeof successCallback == 'function') {
            if (newWindow) {
                newWindow.onload = function() {
                    successCallback(newWindow);
                }
            }
        }
        return false;
    }
};
